package com.example.communist_app_api.db.dao;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.example.communist_app_api.db.pojoDto.NoticeEntity;
import com.example.communist_app_api.db.pojoDto.NoticeRefEntity;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Repository
public class NoticeDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    public static final String COLLECTION_NAME="notice";
    public String insert(NoticeEntity entity){
        //把北京时间转成格林时间再存到MongoDB
        Date sendTime=entity.getSendTime();
        //偏移8个小时
        sendTime=DateUtil.offset(sendTime, DateField.HOUR,8);
        entity.setSendTime(sendTime);
        entity = mongoTemplate.save(entity);
        return entity.get_id();
    }


    public List<HashMap> searchNoticeByPage(int userId){
        JSONObject json=new JSONObject();
        //key-value关系
        json.set("$toString","$_id");
        Aggregation aggregation= Aggregation.newAggregation(
                Aggregation.addFields().addField("id").withValue(json).build(),
                Aggregation.lookup("notice_ref","id","noticeId","ref"),
                Aggregation.match(Criteria.where("ref.receiverId").is(userId)),
                Aggregation.sort(Sort.by(Sort.Direction.DESC,"sendTime"))
 //               , Aggregation.skip(start),
//                Aggregation.limit(length)
        );

        return getHashMaps(aggregation);
    }

    public List<HashMap> searchNoticeByUserIdList(List userIdList){
        Criteria criteria = new Criteria();
        //查询type = 1 或 type = 0 and 正则regex senderName = 组织
        //还需要划分组织来查询
        //type是String类型，要加双引号
        Criteria criteria1 = new Criteria();
        criteria1.orOperator(Criteria.where("type").is("1"),
                new Criteria().andOperator(Criteria.where("type").is("0"),Criteria.where("senderName").regex("组织")));
        criteria.andOperator(criteria1,Criteria.where("senderId").in(userIdList));
        JSONObject json=new JSONObject();
        json.set("$toString","$_id");
        Aggregation aggregation= Aggregation.newAggregation(
                Aggregation.addFields().addField("id").withValue(json).build(),
                Aggregation.lookup("notice_ref","id","noticeId","ref"),
                Aggregation.match(criteria),
                Aggregation.sort(Sort.by(Sort.Direction.DESC,"sendTime"))
        );

        AggregationResults<HashMap> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, HashMap.class);
        List<HashMap> list = results.getMappedResults();
        return list;
    }


    public HashMap searchNoticeById(String id){
        HashMap map = mongoTemplate.findById(id, HashMap.class, COLLECTION_NAME);
        Date sendTime =(Date) map.get("sendTime");
        sendTime=DateUtil.offset(sendTime, DateField.HOUR,-8);
        map.replace("sendTime",DateUtil.format(sendTime,"yyyy/MM/dd HH:mm"));
        return map;
    }


    public long deleteNoticeById(String id) {
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        DeleteResult result = mongoTemplate.remove(query, COLLECTION_NAME);
        long count = result.getDeletedCount();
        return count;
    }

    public List<HashMap> searchNoticeByPageUniApp(int userId, long start, int length) {
        JSONObject json=new JSONObject();
        json.set("$toString","$_id");
        Aggregation aggregation= Aggregation.newAggregation(
                Aggregation.addFields().addField("id").withValue(json).build(),
                Aggregation.lookup("notice_ref","id","noticeId","ref"),
                Aggregation.match(Criteria.where("ref.receiverId").is(userId)),
                Aggregation.sort(Sort.by(Sort.Direction.DESC,"sendTime"))
                               , Aggregation.skip(start),
                Aggregation.limit(length)
        );

        return getHashMaps(aggregation);
    }

    private List<HashMap> getHashMaps(Aggregation aggregation) {
        AggregationResults<HashMap> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, HashMap.class);
        List<HashMap> list = results.getMappedResults();
        list.forEach(one->{
            List<NoticeRefEntity> refList =(List<NoticeRefEntity>) one.get("ref");
            if(refList.size()==0){
                return;
            }
            NoticeRefEntity entity = refList.get(0);
            Boolean readFlag = entity.getReadFlag();
            String refId = entity.get_id();
            one.put("readFlag",readFlag);
            one.put("refId",refId);
            one.remove("ref");
            one.remove("_id");

            Date sendTime =(Date) one.get("sendTime");
            sendTime= DateUtil.offset(sendTime, DateField.HOUR,-8);

            String today=DateUtil.today();
            if(today.equals(DateUtil.date(sendTime).toDateStr())){
                one.put("sendTime",DateUtil.format(sendTime,"HH:mm"));
            }else {
                one.put("sendTime",DateUtil.format(sendTime,"yyyy/MM/dd"));
            }

        });
        return list;
    }
<<<<<<< HEAD

    public List<HashMap> searchMessage(Integer userId,String message) {
        JSONObject json=new JSONObject();
        json.set("$toString","$_id");
        Criteria c1 = new Criteria().andOperator(Criteria.where("ref.receiverId").is(userId));
        Criteria c2 = new Criteria().andOperator(Criteria.where("msg").regex(message));
        Aggregation aggregation= Aggregation.newAggregation(
                Aggregation.addFields().addField("id").withValue(json).build(),
                Aggregation.lookup("notice_ref","id","noticeId","ref"),
                Aggregation.match(new Criteria().andOperator(c1,c2)),
                Aggregation.sort(Sort.by(Sort.Direction.DESC,"sendTime"))
        );
        return getHashMaps(aggregation);
    }

    public List<HashMap> searchNotice(String senderName, String type, Integer userId) {
        JSONObject json=new JSONObject();
        json.set("$toString","$_id");
        Criteria c1 = new Criteria().andOperator(Criteria.where("senderName").is(senderName));
        Criteria c2 = new Criteria().andOperator(Criteria.where("type").is(type));
        Criteria c3 = new Criteria().andOperator(Criteria.where("ref.receiverId").is(userId));
        Aggregation aggregation= Aggregation.newAggregation(
                Aggregation.addFields().addField("id").withValue(json).build(),
                Aggregation.lookup("notice_ref","id","noticeId","ref"),
                Aggregation.match(new Criteria().andOperator(c1,c2,c3)),
                Aggregation.sort(Sort.by(Sort.Direction.DESC,"sendTime"))
        );
        return getHashMaps(aggregation);
    }

    public Boolean unReadFlag(String senderName, String type, Integer userId) {
        Query query=new Query();
        //query的and可以连续追加的，readFlag字段的false有问题，不知道是什么格式
        query.addCriteria(Criteria.where(READ_FLAG).is(false).and(RECEIVER_ID).is(userId));
        List<String> noticeIdList = mongoTemplate.find(query, NoticeRefEntity.class).stream().map(n -> n.getNoticeId()).collect(Collectors.toList());
        Query queryByNoticeIdList=new Query();
        queryByNoticeIdList.addCriteria(Criteria.where("type").is(type).and("senderName").is(senderName).and("_id").in(noticeIdList));
        long count = mongoTemplate.count(queryByNoticeIdList, NoticeEntity.class);
        return count>=1?true:false;
    }

    public List<HashMap> searchMessageBySecondPage(Integer userId, String message, String senderName, String type) {
        JSONObject json=new JSONObject();
        json.set("$toString","$_id");
        Criteria c1 = new Criteria().andOperator(Criteria.where("senderName").is(senderName));
        Criteria c2 = new Criteria().andOperator(Criteria.where("type").is(type));
        Criteria c3 = new Criteria().andOperator(Criteria.where("ref.receiverId").is(userId));
        Criteria c4 = new Criteria().andOperator(Criteria.where("msg").regex(message));
        Aggregation aggregation= Aggregation.newAggregation(
                Aggregation.addFields().addField("id").withValue(json).build(),
                Aggregation.lookup("notice_ref","id","noticeId","ref"),
                Aggregation.match(new Criteria().andOperator(c1,c2,c3,c4)),
                Aggregation.sort(Sort.by(Sort.Direction.DESC,"sendTime"))
        );
        return getHashMaps(aggregation);
    }
}
=======
}
>>>>>>> parent of aec1d46 (消息模块的搭建和配合其他模块消息的发送和收取)
